package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1 调用mapper 根据username查询 如果查询不到 返回错误提示
        Employee employee = employeeMapper.findByUsername(username);

        if (employee == null){
            return ResultInfo.error("用户不存在");
        }

        // 2 将传入的password进行加密  根据查询到的password进行比对
        String passwordWithMd5 = SecureUtil.md5(password);//加密

        if (!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }

        //3 查看用户的status是否为0 禁用状态
        if (employee.getStatus() == Employee.STATUS_DISABLE){
            return ResultInfo.error("当前账号已经被禁用了");
        }

        //4 登录成功 返回employee信息
        return ResultInfo.success(employee);
    }

    // 根据name模糊查询
    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        //1 补齐参数
        Long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);//主键
        employee.setPassword(SecureUtil.md5("123"));//设置123为默认密码
        employee.setStatus(Employee.STATUS_ENABLE);//状态

//        //1-4 创建 修改时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//
//        //1-5 创建 修改人
//        employee.setCreateUser(1L); //临时写死
//        employee.setUpdateUser(1L);

        //  2 调用mapper保存
        employeeMapper.insert(employee);
    }

    @Override
    public Employee finById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
//        //1. 设置两个字段
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);//临时写死

        //2. 调用mapper更新
        employeeMapper.updateById(employee);
    }
}
